package com.four.project.shiro;

import com.four.project.pojo.User;
import com.four.project.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author 梯子君(xie)
 * @Data 2020/7/716:13
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String email = (String) principalCollection.getPrimaryPrincipal();
        //后台多表联查该邮箱所拥有的权限

        // 创建简单授权信息对象将查询出的权限置入
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //将角色放入授权对象
        simpleAuthorizationInfo.addRole("");
        return simpleAuthorizationInfo;
    }
    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取邮箱
        String email = (String)authenticationToken.getPrincipal();
        //去数据库查询用户真实姓名
        User queryUser = userService.findUserByLogin(email);
        //创建一个简单的验证消息对象
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(email,queryUser.getPassword(),getName());

        return simpleAuthenticationInfo;
    }
}
